// 代理服务配置
// 由于百度API的CORS限制，需要使用代理服务

export const PROXY_CONFIG = {
  // 只使用本地代理服务器
  PROXY_URLS: [
    'http://localhost:3002/?url='  // 本地代理服务器
  ],
  
  // 超时时间（毫秒）
  TIMEOUT: 20000,
  
  // 重试次数
  MAX_RETRIES: 1
}

// 使用代理发送请求
export const fetchWithProxy = async (url: string, options: RequestInit = {}) => {
  const { PROXY_URLS, TIMEOUT, MAX_RETRIES } = PROXY_CONFIG
  
  console.log('🔧 使用代理配置:', PROXY_URLS)
  console.log('🎯 目标URL:', url)
  
  for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
    for (const proxyUrl of PROXY_URLS) {
      try {
        console.log(`🔄 尝试代理: ${proxyUrl}`)
        let targetUrl = url
        
        if (proxyUrl.includes('allorigins.win')) {
          targetUrl = `${proxyUrl}${encodeURIComponent(url)}`
        } else if (proxyUrl.includes('localhost:3002')) {
          targetUrl = `${proxyUrl}${encodeURIComponent(url)}`
        } else {
          targetUrl = `${proxyUrl}${url}`
        }
        
        // 添加超时控制
        const controller = new AbortController()
        const timeoutId = setTimeout(() => controller.abort(), TIMEOUT)
        
        const response = await fetch(targetUrl, {
          ...options,
          signal: controller.signal,
          headers: {
            ...options.headers,
            'X-Requested-With': 'XMLHttpRequest'
          }
        })
        
        clearTimeout(timeoutId)
        
        if (response.ok) {
          console.log(`代理请求成功: ${proxyUrl}`)
          // 检查响应内容类型
          const contentType = response.headers.get('content-type')
          console.log(`响应内容类型: ${contentType}`)
          return response
        } else {
          console.warn(`代理请求失败: ${proxyUrl}, 状态码: ${response.status}`)
          // 尝试读取错误响应
          try {
            const errorText = await response.text()
            console.warn(`错误响应内容: ${errorText}`)
          } catch (e) {
            console.warn('无法读取错误响应内容')
          }
        }
        
      } catch (error) {
        console.warn(`代理请求失败: ${proxyUrl}`, error)
        continue
      }
    }
    
    // 如果所有代理都失败，等待一段时间后重试
    if (attempt < MAX_RETRIES - 1) {
      await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)))
    }
  }
  
  throw new Error('所有代理服务都失败了，请检查网络连接或稍后重试')
}
